﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;
using System.Data.SqlClient;
using System.Net;
using Renci.SshNet;
using System.Runtime.InteropServices;
using System.Security.Principal;

namespace SMDS
{
    class GetPassHelper
    {
        // logon types
        const int LOGON32_LOGON_INTERACTIVE = 2; //访问本地授权数据库
        const int LOGON32_LOGON_NETWORK = 3;
        const int LOGON32_LOGON_NEW_CREDENTIALS = 9;

        // logon providers
        const int LOGON32_PROVIDER_DEFAULT = 0;
        const int LOGON32_PROVIDER_WINNT50 = 3;
        const int LOGON32_PROVIDER_WINNT40 = 2;
        const int LOGON32_PROVIDER_WINNT35 = 1;

        [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern int LogonUser(String lpszUserName, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);

        [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern int DuplicateToken(IntPtr hToken, int impersonationLevel, ref IntPtr hNewToken);

        [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern bool RevertToSelf();

        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        public static extern bool CloseHandle(IntPtr handle);


        public static int TimeOut;
        
        public static bool CheckSSH(string ip, int port, string user, string pass)
        {
            try{

                SshClient sft = new SshClient(ip, port, user, pass);
                sft.Connect();
                sft.Disconnect();
                sft.Dispose();
                return true;
            }
            catch(Exception ex){
                Console.WriteLine(ex.Message);
            }
            return false;
        }

        public static bool CheckFTP(string ip, int port, string user, string pass)
        {
            try
            {
                FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ip + ":"  + port.ToString() + "/1.txt"));
                ftp.Timeout=TimeOut;
                ftp.ReadWriteTimeout=TimeOut;
                ftp.UseBinary = true;      
                                                      
                ftp.Credentials = new NetworkCredential(user,pass);
                FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
                response.Close();
                ftp.Abort();
                return true;            
            }
            catch{}
             
            return false;
        }

        public static bool CheckSMB(string ip, int port, string user, string pass)
        {
            IntPtr token = IntPtr.Zero;
            IntPtr tokenDuplicate = IntPtr.Zero;
            WindowsImpersonationContext _CurrentImpersonationContext;
            try
            {
                if (RevertToSelf()) //还原应用程序运行身份
                {
                    //
                    // 这里使用LOGON32_LOGON_NEW_CREDENTIALS来访问远程资源。
                    // 如果要（通过模拟用户获得权限）实现服务器程序，
                    // 访问本地授权数据库可以用LOGON32_LOGON_INTERACTIVE
                    //
                    //if (LogonUser(userName, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref token) != 0)
                    if (LogonUser(user, "\\\\" + ip + ":"+ port+ "\\", pass, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, ref token) != 0)
                    //if (LogonUser(userName, domain, password, LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_DEFAULT, ref token) != 0)
                    {
                        if (DuplicateToken(token, 2, ref tokenDuplicate) != 0) //复制访问令牌
                        {
                            WindowsIdentity tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
                            _CurrentImpersonationContext = tempWindowsIdentity.Impersonate(); //当前扮演的角色

                            //扮演角色成功
                            if (_CurrentImpersonationContext != null)
                            {
                                AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
                                IPrincipal pr = System.Threading.Thread.CurrentPrincipal;
                                IIdentity id = pr.Identity;
                                //其它处理.....

                                CloseHandle(token);
                                CloseHandle(tokenDuplicate);
                                return true;
                            }
                        }
                    }
                }

                if (token != IntPtr.Zero) CloseHandle(token);
                if (tokenDuplicate != IntPtr.Zero) CloseHandle(tokenDuplicate);
            }
            catch (Exception ex)
            {
                Console.WriteLine("GetPassHelper.cs->CheckSMB()",ex.Message);
            }

            return false;
        }


        public static bool CheckMysql(string ip, int port, string user, string pass)
        {

            string str = "server=" + ip + ";port=" + port.ToString() + ";user=" + user + ";password=" + pass +";Connection Timeout=" + TimeOut.ToString();
            try
            {
                using (MySqlConnection conn = new MySqlConnection(str))
                {
                    conn.Open();
                    conn.Close();
                    return true;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("GetPassHelper.cs->CheckMysql()", ex.Message);
            }

            return false;
        }

        public static bool CheckSqlServer(string ip, int port, string user, string pass)
        {
            string str = ";Data Source=" + ip + ";User ID=" + user + ";Password=" + pass +";Connection Timeout=" + TimeOut.ToString();
            try
            {
                using (SqlConnection conn = new SqlConnection(str))
                {
                    conn.Open();
                    conn.Close();
                    return true;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("GetPassHelper.cs->CheckSqlServer()", ex.Message);
            }
            return false;
        }

        public static bool CheckRemote(string ip, int port, string user, string pass)
        {
            return false;
        }


    }
}
